package com.interagriculture.service.impl;

import com.github.pagehelper.PageHelper;
import com.interagriculture.common.Constants;
import com.interagriculture.entity.JournalismMain;
import com.interagriculture.mapper.JournalismMainMapper;
import com.interagriculture.service.JournalismMainService;
import com.interagriculture.utils.UploadFileUtil;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * (JournalismMain)表服务实现类
 *
 * @author makejava
 * @since 2024-11-14 16:21:58
 */
@Service("journalismMainService")
public class JournalismMainServiceImpl implements JournalismMainService {
    @Resource
    private JournalismMainMapper journalismMainMapper;
    @Resource
    private UploadFileUtil uploadFileUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JournalismMain queryById(Integer id) {
        return this.journalismMainMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param journalismMain 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<JournalismMain> queryByPage(JournalismMain journalismMain, PageRequest pageRequest) {
        long total = this.journalismMainMapper.count(journalismMain);
        return new PageImpl<>(this.journalismMainMapper.queryAllByLimit(journalismMain, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param journalismMain 实例对象
     * @return 实例对象
     */
    @Override
    public JournalismMain insert(JournalismMain journalismMain) {
        this.journalismMainMapper.insert(journalismMain);
        return journalismMain;
    }

    /**
     * 修改数据
     *
     * @param journalismMain 实例对象
     * @return 实例对象
     */
    @Override
    public JournalismMain update(JournalismMain journalismMain) {
        this.journalismMainMapper.update(journalismMain);
        return this.queryById(journalismMain.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.journalismMainMapper.deleteById(id) > 0;
    }

    @Override
    public void saveOrUpdateMain(JournalismMain journalismMain, MultipartFile picture) {
        if(journalismMain.getId()==null){
            journalismMainMapper.insertOrUpdate(journalismMain);
        }
        String search = uploadFileUtil.uploadUserFile(Constants.JOURNALISM, journalismMain.getId(), picture);
        journalismMain.setPicture(search);
        journalismMainMapper.update(journalismMain);
    }


}
